package com.xm.web.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.lang.tree.parser.DefaultNodeParser;
import cn.hutool.core.map.MapUtil;
import com.xm.common.utils.StrPool;
import com.xm.web.consts.MagicNumEnum;
import com.xm.web.entity.po.TbPermission;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 简化权限结构处理
 *
 * @author yousj
 * @since 2022-03-22
 */
public class PermissionTreeUtil {

    private static TreeNodeConfig treeNodeConfig;

    static {
        treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setWeightKey(StrPool.SORT);
        treeNodeConfig.setDeep(MagicNumEnum.MAX_DEEP.getCode());
    }

    public static List<Tree<Integer>> permissions2tree(List<TbPermission> permissionList) {
        if (CollectionUtil.isEmpty(permissionList)) throw new RuntimeException();
        return TreeUtil.build(
                permissionList.stream().map(p ->
                        new TreeNode<>(p.getId(), p.getParentId(), p.getPermissionName(), p.getSort())
                                .setExtra(MapUtil.<String, Object>builder()
                                        .put(StrPool.ROUTER, p.getPermissionRouter())
                                        .put(StrPool.TYPE, p.getPermissionType())
                                        .put(StrPool.ICON, p.getIcon())
                                        .build()
                                )
        ).collect(Collectors.toList()),
                MagicNumEnum.ROOT.getCode(), treeNodeConfig, new DefaultNodeParser<>());
    }

    public static void getAllEndRules(List<Tree<Integer>> trees, List<Integer> allEndRules) {
        if (Objects.nonNull(trees)) {
            for (Tree<Integer> tree : trees) {
                if (Objects.isNull(tree.getChildren())) {
                    allEndRules.add(tree.getId());
                    continue;
                }
                getAllEndRules(tree.getChildren(), allEndRules);
            }
        }
    }

    public static void getAllParentMenuIds(List<Tree<Integer>> trees, Integer id, List<Integer> allParentMenuIds) {
        if (Objects.nonNull(trees)) {
            for (Tree<Integer> tree : trees) {
                if (!Objects.equals(tree.getId(), id)) {
                    getAllParentMenuIds(tree.getChildren(), id, allParentMenuIds);
                } else {
                    while (Objects.nonNull(tree.getParent())
                            && !Objects.equals(tree.getParent().getId(), MagicNumEnum.ROOT.getCode())) {
                        tree = tree.getParent();
                        allParentMenuIds.add(tree.getId());
                    }
                }
            }
        }
    }

}
